﻿#region Usings

using System;
using System.Configuration;
using System.Threading;
using Castle.MonoRail.Framework;
using Rodunu.Movies.Contracts;
using Rodunu.Movies.Interfaces.Security;
using Rodunu.Movies.Interfaces.User;
using Rodunu.Movies.Logic.User;
using Rodunu.Movies.Security;
using Rodunu.Movies.Web.Filters;
using Rodunu.Movies.Web.Security;

#endregion

namespace Rodunu.Movies.Web.Controllers
{
    [Rescue("generalerror")]
    //[Filter(ExecuteEnum.BeforeAction, typeof(AuthenticationFilter), ExecutionOrder = 1)]
    public abstract class BaseController : SmartDispatcherController
    {
        #region Private Members

        private readonly IUserAuthentication securityService;
        private readonly WebAuthentication _webAuthentication;
        private IUser _userLogic;

        #endregion

        #region Constructor

        protected BaseController()
        {
            securityService = new UserAuthentication();
            _webAuthentication = new WebAuthentication();
        }

        #endregion

        public void SetUser()
        {
            //long userId = 0;
            //if (ConfigurationManager.AppSettings["LoggedOnUser"] != null)
            //    userId = Convert.ToInt64(ConfigurationManager.AppSettings["LoggedOnUser"]);
            //else if (HttpContext.Request != null)
            //    userId = Convert.ToInt64(Request.ReadCookie("RodunuCookie"));

            ////"RodunuCookie"
            //if (User == null || User.Id == 0)
            //    LogUserInFromCookie(userId, this);

            //SetLastLogginDate();

            //if (User != null && User.Id > 0)
            //    SetUserLoggedIn();
        }

        public UserInfo User
        {
            get
            {
                if (Session["CurrentUser"] == null)
                {
                    long userId = 0;
                    if (ConfigurationManager.AppSettings["LoggedOnUser"] != null)
                        userId = Convert.ToInt64(ConfigurationManager.AppSettings["LoggedOnUser"]);
                    else if (HttpContext.Request != null)
                        userId = Convert.ToInt64(Request.ReadCookie("RodunuCookie"));

                    if (userId <= 0)
                        return CreateGuestUser();

                    IUser userLogic = new UserLogic();
                    UserInfo user = userLogic.Find(userId);
                    _webAuthentication.SetAuthCookie(user, true, string.Empty, Response);

                    if (Session["LastLoginDate"] == null)
                        Session["LastLoginDate"] = user.LoggedInDate;

                    user.IsLoggedIn = true;
                    user.IsLoaded = true;
                    PropertyBag["authCookieContent"] = userId;
                    Session["CurrentUser"] = user;
                }
                return (UserInfo) Session["CurrentUser"];
            }
            set
            {
                Session["CurrentUser"] = value;
            }
        }

        //public UserInfo User
        //{
        //    get
        //    {
        //        try
        //        {
        //            if (Session == null || Session[WebConstants.USERSESSIONKEY] == null)
        //                return CreateGuestUser();
        //        }
        //        catch (Exception)
        //        {
        //            return CreateGuestUser();
        //        }
        //        return (UserInfo)Session[WebConstants.USERSESSIONKEY];
        //    }
        //    set { Session[WebConstants.USERSESSIONKEY] = value; }
        //}

        public DateTime? LastLoginDate
        {
            get
            {
                if (Session["LastLoginDate"] != null)
                    return (DateTime) Session["LastLoginDate"];
                return User.LoggedInDate;
            }
        }

        #region Private Methods

        private static UserInfo CreateGuestUser()
        {
            UserInfo user;
            user = new UserInfo();
            user.IsLoggedIn = false;
            //if (Session != null)
            //    Session[WebConstants.USERSESSIONKEY] = user;
            return user;
        }

        private bool LogUserInFromCookie(long userId, Controller controller)
        {
            if (userId > 0)
            {
                UserInfo user = securityService.ReValidate(userId);
                user.IsLoggedIn = true;
                user.IsLoaded = true;

                //context.CurrentUser = user;
                _webAuthentication.SetAuthCookie(user, true, string.Empty, Response);
                Thread.CurrentPrincipal = user;
                controller.PropertyBag["authCookieContent"] = userId;

                User = user;
                return true;
            }
            User = CreateGuestUser();
            return false;
        }

        private static bool NotLoggedUser()
        {
            var nlUser = new UserInfo();
            nlUser.IsLoggedIn = false;
            nlUser.UserName = "Guest";
            Thread.CurrentPrincipal = nlUser;
            return true;
        }

        private void SetUserLoggedIn()
        {
            if (_userLogic == null)
                _userLogic = new UserLogic();

            _userLogic.SetLogin(User.Id);
        }

        private void SetLastLogginDate()
        {
            if (Session["LastLoginDate"] == null)
            {
                if (User != null && User.Id > 0)
                {
                    if (_userLogic == null)
                        _userLogic = new UserLogic();

                    Session["LastLoginDate"] = _userLogic.Find(User.Id).LoggedInDate;
                }
            }
        }

        #endregion

    }
}
